#include "precompile.h"

#include "AddinManager.h"
#include "IAddin.h"
#include "sys/io/Directory.h"
#include "sys/io/Path.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

AddinManager::AddinManager()
{
}

AddinManager::~AddinManager()
{
}

vresult  AddinManager::LoadAll()
{
	if (ISFAILED(LoadByCategory(L"extensions")))
		return vfailed;

	if (ISFAILED(LoadByCategory(L"addins")))
		return vfailed;

	return vok;
}

void AddinManager::UnloadAll()
{
	AddinDictionary::const_iterator itbegin = m_addins.begin();
	AddinDictionary::const_iterator itend = m_addins.end();
	for (; itbegin != itend; ++itbegin)
	{
		IObject* addin = itbegin->second;
		sys::InterfacePtr<IAddin> pIFAddin(addin);
		pIFAddin->Unload();
	}
}

//////////////////////////////////////////////////////////////////////////
//private methods
vresult AddinManager::LoadByCategory(const String& category)
{
	String extensionFolder = io::Path::CombinePath(io::Path::GetExeDirectory(),category);

	StringArray files;
	if (!io::Directory::GetFiles(files,extensionFolder,L"*.xpln",true))
		return vok;

	StringArray::const_iterator itbegin = files.begin();
	StringArray::const_iterator itend = files.end();
	for (; itbegin != itend; ++itbegin)
	{
		if (ISFAILED(Load(itbegin->c_str())))
			continue;
	}
	return vok;
}

vresult  AddinManager::Load(const String& path)
{
	IObject* objAddin = ::LoadAddin(path.c_str());
	if (!objAddin)
		return vfailed;

	sys::InterfacePtr<IAddin> pIFAddin(objAddin);
	if (pIFAddin->Load())
	{
		m_addins[path] = objAddin;
		return vok;
	}

	return vfailed;
}

void AddinManager::Unload(const String& path)
{
	::UnloadComponent(path.c_str());
}